﻿using System.IO;
using System.Linq;
using System.Xml.Linq;
using System.Runtime.Serialization.Formatters.Soap;
using System.Runtime.Serialization;

namespace PengSW.Serialize
{
    public static class Serializer
    {
        public static void SerializeTo<T>(this T aObject, Stream aStream, IFormatter aFormatter = null)
        {
            if (aFormatter == null) aFormatter = new SoapFormatter();
            aFormatter.Serialize(aStream, aObject);
        }

        public static void SerializeTo<T>(this T aObject, string aFileName, IFormatter aFormatter = null)
        {
            using (FileStream aStream = new FileStream(aFileName, FileMode.Create, FileAccess.Write))
            {
                SerializeTo(aObject, aStream, aFormatter);
                aStream.Close();
            }
        }

        public static T SerializeFrom<T>(Stream aStream, IFormatter aFormatter = null)
        {
            T aObject = default(T);
            if (aFormatter == null) aFormatter = new SoapFormatter();
            aObject = (T)aFormatter.Deserialize(aStream);
            return aObject;
        }

        public static T SerializeFrom<T>(string aFileName, IFormatter aFormatter = null)
        {
            T aObject = default(T);
            using (FileStream aStream = new FileStream(aFileName, FileMode.Open, FileAccess.Read))
            {
                aObject = SerializeFrom<T>(aStream, aFormatter);
                aStream.Close();
            }
            return aObject;
        }
    }
}
